﻿#include "form_health.h"
#include "ui_form_health.h"

#include <QFile>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QPushButton>
#include <QTimer>
#include <QDir>
#include <topo_info.h>
#include <com_manager.h>

#if _MSC_VER >= 1600
#pragma execution_character_set("utf-8")
#endif



#define TIMER_TIMEOUT   (300)  

struct NODE_STAT
{
	QString _id;

	QString _type;
	QString _value;

	QString _hz;
	QString _phase;
	QString _op;

	NODE_STAT() {}

	NODE_STAT(QString _1, QString _2, QString _3, QString _4, QString _5, QString _6)
	{
		_id = _1;

		_type = _2;
		_value = _3;

		_hz = _4;
		_phase = _5;
		_op = _6;
	}

	QJsonObject toJson()
	{
		QJsonObject jObj;
		jObj.insert("_id", _id);
		jObj.insert("_type", _type);
		jObj.insert("_value", _value);
		jObj.insert("_hz", _hz);
		jObj.insert("_phase", _phase);
		jObj.insert("_op", _op);

		return jObj;
	}

	void fromJson(QJsonObject obj)
	{
		_id = obj.value("_id").toString();
		_type = obj.value("_type").toString();
		_value = obj.value("_value").toString();
		_hz = obj.value("_hz").toString();
		_phase = obj.value("_phase").toString();
		_op = obj.value("_op").toString();
	}

};

QStringList HEADER = { "序号", "节点", "接口类型", "节点值", "节点频率", "节点相位偏移", "操作" };
QMap<QString, NODE_STAT*> statistic_info// = new Dictionary<string, SEGMENT>
{
{ "节点1", new NODE_STAT("节点1","以太网",     "主节点", "192.168.1.1","正常","查看详情") },
{ "节点2", new NODE_STAT("节点2","以太网",      "主节点","192.168.1.2","正常","查看详情") },
{ "节点3", new NODE_STAT("节点3","以太网",      "主节点","192.168.1.3","正常","查看详情") },
{ "节点4", new NODE_STAT("节点4","以太网",      "主节点","192.168.1.4","正常","查看详情") },
{ "节点5", new NODE_STAT("节点5","以太网",      "主节点","192.168.1.5","正常","查看详情") },
{ "节点6", new NODE_STAT("节点6","以太网",      "主节点","192.168.1.6","正常","查看详情") },
{ "节点7", new NODE_STAT("节点7","以太网",      "主节点","192.168.1.7","正常","查看详情") },
{ "节点8", new NODE_STAT("节点8","以太网",      "主节点","192.168.1.8","异常","查看详情") },
{ "节点9", new NODE_STAT("节点9","以太网",      "主节点","192.168.1.9","正常","查看详情") },
{ "节点10", new NODE_STAT("节点10","PowerLink", "主节点","192.168.1.10","正常","查看详情") },
{ "节点11", new NODE_STAT("节点11","PowerLink", "主节点","192.168.1.10","正常","查看详情") },
{ "节点12", new NODE_STAT("节点12","PowerLink", "从节点","192.168.1.10","异常","查看详情") },
{ "节点13", new NODE_STAT("节点13","PowerLink", "从节点","192.168.1.10","正常","查看详情") },
{ "节点14", new NODE_STAT("节点14","PowerLink", "从节点","192.168.1.10","正常","查看详情") },
{ "节点15", new NODE_STAT("节点15","PowerLink", "从节点","192.168.1.10","正常","查看详情") },
{ "节点16", new NODE_STAT("节点16","PowerLink", "从节点","192.168.1.10","正常","查看详情") },
{ "节点17", new NODE_STAT("节点17","CAN",       "从节点", "",			"正常","查看详情") },
{ "节点18", new NODE_STAT("节点18","CAN",       "从节点", "",			"正常","查看详情") },
{ "节点19", new NODE_STAT("节点19","CAN",       "从节点", "",			"正常","查看详情") },
{ "节点20", new NODE_STAT("节点20","CAN",       "主节点","",			"正常","查看详情") },
{ "节点21", new NODE_STAT("节点21","RS485",		"主节点","",			"正常","查看详情") },
{ "节点22", new NODE_STAT("节点22","RS485",		"主节点", "",			"正常","查看详情") },
{ "节点23", new NODE_STAT("节点23","RS485",		"主节点","",			"正常","查看详情") }
};



void FormHealth::saveJson()
{
	QDir dir(qApp->applicationDirPath());
	if (!dir.exists("data"))
		dir.mkpath("data");


	QJsonArray headerArray;
	QStringList header_label;
	header_label << "序号" << "操作ID" << "故障设备" << "故障时间" << "故障原因" << "故障等级" << "是否处理" << "操作时间" << "操作";
	//headerArray.fromStringList(header_label);
	foreach(QString str, header_label)
	{
		headerArray.append(str);

	}

	QJsonArray dataArray;

	QMap<QString, NODE_STAT*> ::iterator it = statistic_info.begin();
	int row = 0;
	for (; it != statistic_info.end(); ++it, row++)
	{
		NODE_STAT* segment = it.value();

		// foreach(NODE_STAT * json, statistic_info) {
		dataArray.append(segment->toJson());
	}

	QJsonObject content;
	content["header"] = headerArray;
	content["data"] = dataArray;

	QFile fileArray(QApplication::applicationDirPath() + "/data/jsonStatistic.json");
	if (fileArray.open(QIODevice::ReadWrite))
	{
		QByteArray bytes = QJsonDocument(content).toJson();
		fileArray.write(bytes);
		fileArray.close();
	}

}

bool FormHealth::readJson()
{

	QFile fileArray(QApplication::applicationDirPath() + "/data/jsonStatistic.json");
	if (fileArray.open(QIODevice::ReadOnly))
	{
		statistic_info.clear();

		QByteArray bytes = fileArray.readAll();
		QJsonDocument doc = QJsonDocument::fromJson(bytes);

		QJsonObject Array = doc.object();
		QJsonArray headerArray = Array.value("header").toArray();
		QJsonArray dataArray = Array.value("data").toArray();

		int cnt = dataArray.count();
		for (int i = 0; i < cnt; i++)
		{
			QJsonObject  obj = dataArray.at(i).toObject();
			NODE_STAT* fault = new NODE_STAT;
			fault->fromJson(obj);
			statistic_info[fault->_id] = fault;
		}

		return true;
	}
	return false;
}


FormHealth::FormHealth(QWidget* parent)
	: QWidget(parent)
    , ui(new Ui::FormHealth)
{
	ui->setupUi(this);

	if (!readJson())
		saveJson();

    //ui->widget->init_flowchart_view("AOP-301");



    init_tableview();

    // ui->tableView->setModel(model_data);

    // ui->tableView->resizeColumnsToContents();

	ui->tableView->setColumnWidth(0, 80);
	ui->tableView->setColumnWidth(1, 80);
	ui->tableView->setColumnWidth(2, 80);
    ui->tableView->setColumnWidth(3, 180);
	ui->tableView->setColumnWidth(4, 180);
	ui->tableView->setColumnWidth(5, 180);

	ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);

	///////////////////////////
	QPixmap p1;
	p1.load(":/UI/UI/status_7@1x.png");

	QPixmap p2;
	p2.load(":/UI/UI/status_8@1x.png");

#ifdef SERIAL

    QTimer *  mTimer = new QTimer;//初始化定时器对象
    connect(mTimer, &QTimer::timeout, this, [=] {
        QString com_name = com_manager::instance()->curComName;//comList.first();
        rs232com* rs232=   com_manager::instance()->get_com(com_name);
        if(rs232)
        {
            int cnt =   rs232-> query_node_count();
            if( cnt == 0 )
            {
                TopoInfo::Instance()->node_map.clear();
            }
            else
            {// if(  TopoInfo::Instance()->node_map.count() !=0)            {
                TopoInfo::Instance()->query_node_info();              
            }
            ui->widget_topo->on_node_changed();
            update_tableview();
        }
    });

   mTimer->start(1000);//每隔一秒发送一次数据
#endif
    // QList<QLabel*> pumpList;
    // for (int i = 0; i < 6; i++)
    // {
    // 	QLabel* pump = new QLabel();
    // 	pump->setParent(ui->label_5);
    // 	pump->lower();

    // 	pumpList.append(pump);
    // }

    // QRect rect_1(1200 - 960, 340, 75, 75);

    // pumpList[0]->setGeometry(rect_1);
    // pumpList[0]->setPixmap(p2);
    // pumpList[0]->setStyleSheet("background-color:rgba(255,0,0,128);");

    // QRect rect_2(1370 - 960, 240, 75, 75);
    // pumpList[1]->setGeometry(rect_2);
    // pumpList[1]->setPixmap(p1);

    // QRect rect_3(1538 - 960, 300, 75, 75);
    // pumpList[2]->setGeometry(rect_3);
    // pumpList[2]->setPixmap(p1);

    // QRect rect_4(1540 - 960, 500 - 10, 75, 75);
    // pumpList[3]->setGeometry(rect_4);
    // pumpList[3]->setPixmap(p2);

    // QRect rect_5(1380 - 960, 555 - 20, 75, 75);
    // pumpList[4]->setGeometry(rect_5);
    // pumpList[4]->setPixmap(p1);

    // QRect rect_6(1222 - 960, 500 - 20, 75, 75);
    // pumpList[5]->setGeometry(rect_6);
    // pumpList[5]->setPixmap(p1);

    // QTimer* timer = new QTimer(this);
    // connect(timer, &QTimer::timeout, [=]
    // 	{
    // 		static int n = 0;
    // 		if (n & 1)
    // 			pumpList[0]->setStyleSheet("background-color:rgba(255,0,0,128);");
    // 		else
    // 			pumpList[0]->setStyleSheet("background-color:rgba(255,0,0,0);");
    // 		n++;
    // 	});

    // timer->start(TIMER_TIMEOUT);

}

FormHealth::~FormHealth()
{
	delete ui;
}
void FormHealth::init_tableview()
{

    // model_data = new QStandardItemModel;
    // model_data->setHorizontalHeaderLabels(HEADER);
    // model_data->setRowCount(statistic_info.count());
    model_data = new QStandardItemModel;
    QStringList header_labs = { "序号", "节点", "串口号", "mac 地址", "节点频率", "节点相位偏移", "操作" };
    model_data->setHorizontalHeaderLabels(header_labs);
    model_data->setRowCount(statistic_info.count());


	update_tableview();

    // int row = 0;
    // QMap<QString, NODE_STAT*> ::iterator it = statistic_info.begin();

	// for (; it != statistic_info.end(); ++it, row++)
	// {

	// 	QModelIndex index_6 = model_data->index(row, 6);

	// 	QPushButton* btn = new QPushButton("查看详情");
	// 	ui->tableView->setIndexWidget(index_6, btn);

	// 	connect(btn, &QPushButton::clicked, [=] {

	// 		saveJson();

	// 		update_tableview();
	// 		});

	// 	row++;
	// }

	ui->tableView->setModel(model_data);

	ui->tableView->resizeColumnsToContents();
}


void FormHealth::update_tableview()
{

    QMap<int, TOPO_NODE *>::Iterator it = TopoInfo::Instance()->node_map.begin();

    int cnt =  TopoInfo::Instance()->node_map.count();
    model_data->setRowCount(cnt);
    int row =0;
    while ( it !=TopoInfo::Instance()->node_map.end())
    {
        TOPO_NODE * node = it.value();

        QModelIndex index_0 = model_data->index(row, 0);
        model_data->setData(index_0, row + 1 );

        QModelIndex index_1 = model_data->index(row, 1);
        model_data->setData(index_1, node->_id );

        QModelIndex index_2 = model_data->index(row, 2);
        model_data->setData(index_2, node->comName );

        QModelIndex index_3 = model_data->index(row, 3);
        model_data->setData(index_3, node->mac_id);



        row++;
        it ++;
    }

    return;
    // int row = 0;

    // QMap<QString, NODE_STAT*> ::iterator it = statistic_info.begin();

    // for (; it != statistic_info.end(); ++it, row++)
    // {
    // 	NODE_STAT* segment = it.value();

    // 	QModelIndex index_0 = model_data->index(row, 0);
    // 	model_data->setData(index_0, row + 1);

    // 	QModelIndex index_1 = model_data->index(row, 1);
    // 	model_data->setData(index_1, segment->_id);

    // 	QModelIndex index_2 = model_data->index(row, 2);
    // 	model_data->setData(index_2, segment->_type);

    // 	QModelIndex index_3 = model_data->index(row, 3);
    // 	model_data->setData(index_3, segment->_value);

    // 	QModelIndex index_4 = model_data->index(row, 4);
    // 	model_data->setData(index_4, segment->_hz);

    // 	QModelIndex index_5 = model_data->index(row, 5);
 //        model_data->setData(index_5, segment->_phase);

    // 	// QModelIndex index_6 = model_data->index(row, 6);
    // 	// model_data->setData(index_6, segment->_op);
    // }
}


bool FormHealth::event(QEvent *event)
{
    if (event->type() == QEvent::WindowUnblocked)
    {
        this->update_tableview();
    //return true;
    }
      return QWidget::event(event);
}
